<template>
  <div class="admin-page">
    <!-- 登录弹窗：进入页面若未登录则弹窗 -->
    <el-dialog v-model="loginDialogVisible" title="登录" width="420px" align-center destroy-on-close>
      <div class="login-form">
        <label class="field">
          <span class="k">账号</span>
          <input v-model="loginForm.account" type="text" placeholder="请输入账号" />
        </label>
        <label class="field">
          <span class="k">密码</span>
          <input v-model="loginForm.passwordHash" type="password" placeholder="请输入密码" />
        </label>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="loginDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="doLogin">登录</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 左右布局 -->
    <div class="layout">
      <!-- 左侧导航 -->
      <aside class="sidebar">
        <div class="sidebar-title">考试系统管理</div>
        <ul class="nav">
          <li :class="{ active: activeTab === 'papers' }" @click="activeTab = 'papers'">试卷</li>
          <li :class="{ active: activeTab === 'questions' }" @click="activeTab = 'questions'">题目</li>
          <li :class="{ active: activeTab === 'candidates' }" @click="activeTab = 'candidates'">考生</li>
          <li :class="{ active: activeTab === 'stats' }" @click="activeTab = 'stats'">考试情况</li>
        </ul>
      </aside>

      <!-- 右侧内容：拆分为独立组件 -->
      <main class="content">
        <PaperAdmin v-if="activeTab === 'papers'" :key="refreshKey" />
        <QuestionAdmin v-if="activeTab === 'questions'" />
        <CandidateAdmin v-if="activeTab === 'candidates'" />
        <StatsAdmin v-if="activeTab === 'stats'" />
      </main>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { loginUser } from '@/api/chat/user'
import PaperAdmin from '@/components/exam/PaperAdmin.vue'
import QuestionAdmin from '@/components/exam/QuestionAdmin.vue'
import CandidateAdmin from '@/components/exam/CandidateAdmin.vue'
import StatsAdmin from '@/components/exam/StatsAdmin.vue'

const router = useRouter()

// 登录相关
const loginDialogVisible = ref(false)
const loginForm = reactive({
  account: '',
  passwordHash: '',
})

async function doLogin() {
  if (!loginForm.account) {
    ElMessage.warning('请输入账号')
    return
  }
  if (!loginForm.passwordHash) {
    ElMessage.warning('请输入密码')
    return
  }
  try {
    const res = await loginUser({
      account: loginForm.account,
      passwordHash: loginForm.passwordHash,
    } as any)
    const token = res?.data?.data?.token ?? res?.data?.token ?? res?.data?.data?.jwt
    const level = res?.data?.data?.level ?? res?.data?.level
    if (level === 1 || level === 2) {
      if (token) {
        localStorage.setItem('token', String(token))
        localStorage.setItem('sysUser', JSON.stringify(res?.data?.data ?? res?.data))
        ElMessage.success('登录成功')
        loginDialogVisible.value = false
        // 登录成功后刷新子组件（通过 key 触发重挂载）
        refreshKey.value++
      } else {
        ElMessage.error('登录失败：账号不存在')
      }
    } else {
      ElMessage.error('账号不存在')
    }
  } catch (e) {
    ElMessage.error('登录失败')
  }
}

// 页面进入时检查登录
onMounted(() => {
  const token = localStorage.getItem('token')
  if (!token) {
    loginDialogVisible.value = true
  } else {
    refreshKey.value++
  }
})

// 左侧导航
const activeTab = ref<'papers' | 'questions' | 'candidates' | 'stats'>('papers')

// 子组件刷新 key（登录成功后重挂载）
const refreshKey = ref(0)
</script>

<style scoped>
.admin-page {
  min-height: 100vh;
  background: #f5f6f8;
  padding: 20px;
  box-sizing: border-box;
}

.layout {
  display: grid;
  grid-template-columns: 240px 1fr;
  gap: 16px;
  align-items: start;
}

.sidebar {
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 10px;
  padding: 14px 12px;
}

.sidebar-title {
  font-weight: 600;
  margin-bottom: 10px;
}

.nav {
  list-style: none;
  padding: 0;
  margin: 0;
}

.nav li {
  padding: 10px 12px;
  border-radius: 8px;
  cursor: pointer;
}

.nav li:hover {
  background: #f5f6f8;
}

.nav li.active {
  background: #eef2ff;
  color: #1d4ed8;
}

.content {
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 10px;
  padding: 12px;
}

.card {
  display: block;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 6px 12px 6px;
  border-bottom: 1px solid #f0f0f0;
}

.card-header .title {
  font-weight: 600;
}

.card-header .ops {
  display: flex;
  gap: 8px;
  align-items: center;
}

.card-body {
  padding-top: 12px;
}

.pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.placeholder {
  color: #666;
}

.login-form {
  display: grid;
  gap: 10px;
}

.field {
  display: grid;
  gap: 6px;
}

.k {
  font-size: 13px;
  color: #666;
}

.dialog-footer {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}
</style>
